const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const SvgSpritePlugin = require('svg-sprite-loader/plugin');

module.exports = function (env, argv) {
  const { prod: isProd } = env;
  const { mode } = argv;
  const oPath = isProd ? "build" : "dist";

  console.log(env, argv);
  return {
    mode,
    entry: "./src/index.js",
    output: {
      path: path.resolve(__dirname, oPath),
      filename: "main.js",
    },
    plugins: [
      new CleanWebpackPlugin({
        cleanAfterEveryBuildPatterns: [oPath],
      }),
      !isProd &&
        new HtmlWebpackPlugin({
          template: "./src/index.html",
        }),
      new SvgSpritePlugin(), // need when extract: true
    ].filter(Boolean),
    devServer: {
      contentBase: path.join(__dirname, "dist"),
      port: 3000,
      hotOnly: true,
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /(node_modules|bower_components)/,
          loader: "babel-loader",
        },
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"],
        },
        {
          test: /\.svg$/,
          use: {
            loader: "svg-sprite-loader",
            options: {
              symbolId: "svg-[name]",
              // 抽取 sprite.svg 放 cdn 存在跨域问题，可以通过 ajax 拉取
              // 或关闭此选项，使用 inline 模式 注入 sprite
              extract: true,
            },
          },
        },
      ],
    },
  };
};
